<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

class BaseController extends Controller
{
    /**
     * JSON数据返回
     * @param $result
     * @return JsonResponse
     */
    public function apiResult($result): JsonResponse
    {
        return response()->json($result);
    }

    /**
     * 上传文件，返回文件链接
     * @param $file
     * @param $path
     * @return string
     */
    public function upload($path,$file): string
    {
        $diskConfig = Config::get('filesystems.default');
        $disk = Storage::disk($diskConfig);
        switch ($diskConfig){
            case 'qiniu':
                $fileInfo = $disk->put($path, $file);
                return $disk->getAdapter()->getUrl($fileInfo);
            case 'cos':
                $fileInfo = $disk->put($path, fopen($file,'r'));
                if (!$fileInfo){
                    return $this->apiResult(['code'=>1,'message'=>'有错误发生！']);
                }
                return $disk->url($path);
            default:
                return env('APP_URL').'/'.$file->store($path);
        }
    }
}
